﻿namespace IntellectShop.Common
{
	using System;
	using System.Configuration;
	using System.Web;

	public class Globals
	{
		public const string AdministratorRoleName = "Administrator";

		private const string OwnerSessionKey = "OwnerId";

		const string ApplicationServicesConnectionStringDefaultParamName = "ApplicationServices";
		public static string ApplicationServicesConnectionString
		{
			get
			{
				if (ConfigurationManager.ConnectionStrings[ApplicationServicesConnectionStringDefaultParamName] != null)
				{
					return ConfigurationManager.ConnectionStrings[ApplicationServicesConnectionStringDefaultParamName].ConnectionString;
				}
				else
				{
					return null;
				}
			}
		}

		const string ConnectionStringDefaultParamName = "IntellectShop";
		public static string ConnectionString
		{
			get
			{
				if (ConfigurationManager.ConnectionStrings[ConnectionStringDefaultParamName] != null)
				{
					return ConfigurationManager.ConnectionStrings[ConnectionStringDefaultParamName].ConnectionString;
				}
				else
				{
					return null;
				}
			}
		}

		const string TimeZoneParamName = "TimeZone";
		private static TimeZoneInfo timeZone = null;
		public static TimeZoneInfo TimeZone
		{
			get
			{
				if (timeZone == null)
				{
					string timeZoneValue = ConfigurationManager.AppSettings[TimeZoneParamName];
					if (timeZoneValue == null)
					{
						throw new Exception(String.Format("Parameter '{0}' not set in config file.", TimeZoneParamName));
					}

					return TimeZoneInfo.FindSystemTimeZoneById(timeZoneValue);
				}

				return timeZone;
			}

			set
			{
				timeZone = value;
			}
		}

		public static string GetOwnerID(HttpContextBase context)
		{
			if (context.Session[OwnerSessionKey] == null)
			{
				if (!string.IsNullOrEmpty(context.User.Identity.Name))
				{
					// User is logged in, associate the cart with there username
					context.Session[OwnerSessionKey] = context.User.Identity.Name;
				}
				else
				{
					// Generate a new random GUID using System.Guid Class
					Guid tempCartId = Guid.NewGuid();
					// Send tempCartId back to client as a cookie
					context.Session[OwnerSessionKey] = tempCartId.ToString();
				}
			}

			return context.Session[OwnerSessionKey].ToString();
		}

		public static void SetOwnerID(HttpContextBase context, string userID)
		{
			context.Session[OwnerSessionKey] = userID;
		}
	}
}
